package com.daisuxia.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.back.utils.WebClient;
import com.daisuxia.constant.Constant;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.pojo.RiskOrders;
import com.daisuxia.risk.service.IJxlService;
import com.daisuxia.risk.service.IMxService;
import com.daisuxia.risk.service.IRiskCreditUserService;
import com.daisuxia.risk.service.IRiskOrdersService;
import com.daisuxia.risk.service.IZmxyService;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.web.common.reslult.JsonResult;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.MessageTemplate;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IMessageTemplateService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.HttpUtil;
import com.daisuxia.web.util.OrderNoUtil;
import com.daisuxia.web.util.encrypt.AESUtil;

/**
 * 用户运营商认证
 * 
 * @author 2016年12月9日 16:51:09
 * @param
 */
@Controller
public class MxController extends BaseController {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private IMxService mxService;
	@Autowired
	private IRiskCreditUserService riskCreditUserService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IRiskOrdersService riskOrdersService;
	@Autowired
	private IMessageTemplateService messageTemplateService;

	/**
	 * 运营商认证请求
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/credit-web2/verification-jxl")
	public String verificationJxl(HttpServletRequest request, HttpServletResponse response, Model model) {
		String recode = request.getParameter("recode");
		String code = "500";
		String msg = request.getParameter("msg");
		String clientType = request.getParameter("clientType");
		// 66666
		// User user = userService.searchByUserid(836933);
		String telephone = request.getParameter("mobilePhone");
		User user = this.loginFrontUserByDeiceId(request);
		String deviceId = request.getParameter("deviceId");
		if (clientType != null && clientType.equals("ios")) {
			clientType = "ios";
		} else {
			clientType = "andriod";
		}
		try {
			if (user == null) {
				code = "400";
				msg = "请重新登录";
				model.addAttribute("recode", recode);
				model.addAttribute("code", code);
				model.addAttribute("clientType", clientType);
				return "userinfo/mx/userApproveSucc";
			}

			user = userService.searchByUserid(Integer.valueOf(user.getId()));

			if ("2".equals(user.getJxlStatus())) {
				code = "200";
				msg = "用户已认证";
				model.addAttribute("code", code);
				model.addAttribute("recode", recode);
				model.addAttribute("msg", msg);
				model.addAttribute("clientType", clientType);
				return "userinfo/mx/userApproveSucc";
			}

			if ("2".equals(user.getRealname())) {
				code = "600";
				msg = "请进行实名认证";
				model.addAttribute("code", code);
				model.addAttribute("recode", recode);
				model.addAttribute("msg", msg);
				model.addAttribute("clientType", clientType);
				return "userinfo/mx/userApproveSucc";
			}
			// 添加实名认证的判断，防止直接敲url进来
			logger.info("mx getToken success");
		} catch (Exception e) {
			logger.error("mx getToken error deviceId=" + deviceId, e);
			code = "500";
			msg = "系统异常";
		} finally {
			if (recode != null && "300".equals(recode)) {
				msg = "密码错误";
			} else if (recode != null && "400".equals(recode)) {
				msg = "请填写有效数据";
			} else if (recode != null && "500".equals(recode)) {
				msg = "重新发起认证流程";
			}
		}
		model.addAttribute("clientType", clientType);
		model.addAttribute("deviceId", deviceId);
		model.addAttribute("msg", msg);
		model.addAttribute("userPhone", user.getUserPhone());
		model.addAttribute("mobilePhone", telephone);
		return "userinfo/mx/userApprove";
	}

	/**
	 * 运营商认证获得验证码
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/credit-web2/mobileApproveGetCap", method = RequestMethod.POST)
	public void mobileApproveCap(HttpServletRequest request, HttpServletResponse response) {
		String password = request.getParameter("password");
		String deviceId = request.getParameter("deviceId");
		String clientType = request.getParameter("clientType");
		User user = this.loginFrontUserByDeiceId(request);

		// User user = userService.searchByUserid(836933);
		// 6666
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			if (user == null) {
				// 未登录，能否调用APP方法提醒用户登录
				serviceResult = new ServiceResult("400", "用户为空");
			} else {
				if (password != null) {
					user = userService.searchByUserid(Integer.valueOf(user.getId()));
					Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.MX);
					String url1 = keys.get("MX_URL") + "tasks/";
					RiskOrders orders = new RiskOrders();
					String orderNo = OrderNoUtil.getInstance().getUUID();
					orders.setUserId(user.getId());
					orders.setOrderType(ConstantRisk.MX);
					orders.setAct(ConstantRisk.MX_COLLECT);
					orders.setOrderNo(orderNo);
					String value = "{\"account\":\"" + user.getUserPhone() + "\",\"password\":\"" + password + "\",\"user_id\":\"" + user.getId()
							+ "\",\"origin\":\"" + 2 + "\",\"real_name\":\"" + user.getRealname() + "\",\"id_card\":\"" + user.getIdNumber()
							+ "\",\"login_type\":\"pwd\"}";
					orders.setReqParams(value);
					logger.info("send to get applyCollect " + orders.toString());
					riskOrdersService.insert(orders);
					HashMap<String, Object> times = new HashMap<String, Object>();
					times.put("soketOut", 10 * 1000);
					times.put("connOut", 10 * 1000);
					times.put("Authorization", "apikey " + keys.get("MX_APIKEY"));
					String result = WebClient.getInstance().postJsonData(url1, value, times);
					logger.info("get applyCollect result=" + result);
					try {
						if (StringUtils.isNotBlank(result)) {
							orders.setReturnParams(result);
							orders.setStatus(RiskOrders.STATUS_SUC);
							riskOrdersService.update(orders);
							JSONObject jsonObject3 = JSONObject.fromObject(result);
							if (jsonObject3.containsKey("task_id")) {
								String tid = jsonObject3.getString("task_id");
								serviceResult = new ServiceResult(ServiceResult.SUCCESS, "成功", AESUtil.encrypt(tid, null));
							} else {
								serviceResult = new ServiceResult("300", jsonObject3.getString("detail"));
							}
						} else {
							logger.error("mx getCaptcha return null params=" + value);
						}
					} catch (Exception e) {
						logger.error("mx getCaptcha local logic error params=" + value, e);
						serviceResult = new ServiceResult("300", "解析数据出错");
					}
				} else {
					serviceResult.setMsg("密码不能为空");
				}
			}
		} catch (Exception e) {
			logger.error("mobileApprove error ", e);
		}
		SpringUtils.renderJson(response, serviceResult);
	}

	@RequestMapping(value = "/credit-web2/progress", method = RequestMethod.POST)
	public void progress(HttpServletRequest request, HttpServletResponse response) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.MX);
			String url1 = keys.get("MX_URL");
			HashMap<String, String> times = new HashMap<String, String>();
			times.put("Authorization", "apikey " + keys.get("MX_APIKEY"));
			String tid = request.getParameter("tid");
			String result = WebClient.getInstance().doGet(url1 + "/tasks/" + AESUtil.decrypt(tid, null) + "/status", "utf-8", times);
			if (StringUtils.isNotBlank(result)) {
				JSONObject jsonObject = JSONObject.fromObject(result);
				jsonObject.put("tid", tid);
				serviceResult = new ServiceResult(ServiceResult.SUCCESS, "成功", jsonObject);
			}
			System.out.println(result);
		} catch (Exception e) {
			logger.error("progress error ", e);
		}
		SpringUtils.renderJson(response, serviceResult);
	}

	/**
	 * 运营商认证提交验证码
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/credit-web2/mobileApproveSub/{tid}", method = RequestMethod.POST)
	public void mobileApproveSub(HttpServletRequest request, HttpServletResponse response, @PathVariable String tid) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");

		HashMap<String, Object> params = new HashMap<String, Object>();
		User user = this.loginFrontUserByDeiceId(request);
		// 66666

		try {
			if (user == null) {
				serviceResult = new ServiceResult("400", "用户为空");
			} else {
				user = userService.searchByUserid(Integer.valueOf(user.getId()));
				Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.MX);
				String url1 = keys.get("MX_URL");
				HashMap<String, Object> times = new HashMap<String, Object>();
				times.put("Authorization", "apikey " + keys.get("MX_APIKEY"));
				String result = WebClient.getInstance().postJsonData(url1 + "/tasks/" + AESUtil.decrypt(tid, null) + "/input",
						"{\"input\":\"" + request.getParameter("yzm") + "\"}", times);
				logger.info("get applyCollect result=" + result);
				if (StringUtils.isNotBlank(result)) {
					serviceResult = new ServiceResult(ServiceResult.SUCCESS, "成功", tid);

				} else {
					logger.error("mx mobileApproveSub return null userId=" + user.getId());
				}
			}
		} catch (Exception e) {
			logger.error("jxl mobileApprove error ", e);
		}
		SpringUtils.renderJson(response, serviceResult);
	}

	@RequestMapping(value = "/credit-web2/saveTid/{tid}", method = RequestMethod.POST)
	public void saveTid(HttpServletRequest request, HttpServletResponse response, @PathVariable String tid) {
		String xxx = request.getParameter("deviceId");
		String aaa = request.getParameter("userPhone");

		User user = this.loginFrontUserByDeiceId(request);
		// User user = userService.searchByUserid(19);
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {

			if (user == null) {
				serviceResult = new ServiceResult("400", "用户未存在");
			} else {
				if (tid != null) {
					if (user.getId() != null) {
						RiskCreditUser riUser = new RiskCreditUser(Integer.valueOf(user.getId()));
						riUser.setJxlToken(AESUtil.decrypt(tid, null));
						riskCreditUserService.updateJxlToken(riUser);// 认证成功修改用户状态
					}
				}
			}
			serviceResult = new ServiceResult(ServiceResult.SUCCESS, "认证完成！");
		} catch (Exception e) {
			logger.error("saveTid error ", e);
		}
		SpringUtils.renderJson(response, serviceResult);
	}

	/**
	 * 运营商认证找回密码
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/credit-web2/jxlfindPwd")
	public String jxlfindPwd(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "userinfo/mx/findPwd";
	}

	@RequestMapping("/credit-web2/jxlSuccess")
	public String jxlSuccess(HttpServletRequest request, HttpServletResponse response, Model model) {
		String code = request.getParameter("code");
		String clientType = request.getParameter("clientType");
		model.addAttribute("code", code);
		model.addAttribute("clientType", clientType);
		// ServiceResult serviceResult = new ServiceResult("500",
		// "未知异常，请稍后重试！");
		return "userinfo/mx/userApproveSucc";
	}

	@RequestMapping("/credit-web2/findJxlPwdMore")
	public String findJxlPwdMore(HttpServletRequest request, HttpServletResponse response, Model model) {
		// ServiceResult serviceResult = new ServiceResult("500",
		// "未知异常，请稍后重试！");
		String type = request.getParameter("type");
		if (StringUtils.isBlank(type)) {
			type = "1";
		}
		model.addAttribute("type", type);
		return "userinfo/findJxlPwdMore";
	}

	/**
	 * 查询手机号码归属地
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/credit-web2/findMobileBelong")
	public void findMobileBelong(HttpServletRequest request, HttpServletResponse response, Model model) {
		JsonResult rest = new JsonResult(Status.ERROR.getName(), Status.ERROR.getValue());
		try {
			User user = this.loginFrontUserByDeiceId(request);

			user = userService.searchByUserid(Integer.valueOf(user.getId()));
			String phone = request.getParameter("phone");
			if (!StringUtils.isNotBlank(phone)) {
				phone = user.getUserPhone();
			}
			Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.JXL);
			String sendPhone = "";
			String jxlName="";
			String jxlType="";
			//系统原本查询手机归属地api,新号码可能查询有问题 返回格式如下
			//{"msg":"success","result":{"city":"长沙市","cityCode":"0731","mobileNumber":"1536413","operator":"电信CDMA卡","province":"湖南","zipCode":"410000"},"retCode":"200"}
			String url =keys.get("JXL_MOBILE_BELONG")+"?key="+Constant.JXL_FIND_MOBILE_BELONG_KEY+"&phone="+phone;
			String result =HttpUtil.getInstance().doGet(url);
			JSONObject json = null;
			json = JSONObject.fromObject(result);
			JSONObject  obj = null;
			if("200".equals(json.getString("retCode"))){
				obj = json.getJSONObject("result");
                if(obj.getString("operator").contains("联通")){
                	jxlName = "联通";
                	sendPhone = Constant.JXL_PHONE_LT;
                	jxlType = "2";
                }else if(obj.getString("operator").contains("移动")){
                	jxlName = "移动";
                	sendPhone = Constant.JXL_PHONE_YD;
                	jxlType = "1";
                }else{
                	jxlName = "电信";
                	sendPhone = Constant.JXL_PHONE_DX;
                	jxlType = "3";
                }
			}else{
				//如果原系统查询手机归属地API有问题调用淘宝的api返回的json格式如下
			/*			__GetZoneResult_ = {
					    mts:'1731793',
					    province:'上海',
					    catName:'中国电信',
					    telString:'17317937114',
						areaVid:'29423',
						ispVid:'138238560',
						carrier:'上海电信'
					}*/
				String tobaoUrl ="https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel="+phone;
				String tobaoResult =HttpUtil.getInstance().doGet(tobaoUrl);
				String baoResult = tobaoResult.substring(tobaoResult.indexOf("{"));
				obj = JSONObject.fromObject(baoResult);
				if(obj.containsKey("mts")){
	                if(obj.getString("catName").contains("联通")){
	                	jxlName = "联通";
	                	sendPhone = Constant.JXL_PHONE_LT;
	                	jxlType = "2";
	                }else if(obj.getString("catName").contains("移动")){
	                	jxlName = "移动";
	                	sendPhone = Constant.JXL_PHONE_YD;
	                	jxlType = "1";
	                }else{
	                	jxlName = "电信";
	                	sendPhone = Constant.JXL_PHONE_DX;
	                	jxlType = "3";
	                }
	                json.put("retCode", "200");
	                json.put("msg", "success"); 
				}else{
					logger.info("淘宝查询手机归属地API可能已经更新,请尽快更新API");
					json.put("retCode", "20101");
					json.put("msg", "查询不到数据");
				}
			}
	        MessageTemplate mt = new MessageTemplate();
	        MessageTemplate msg = null;
	        if(StringUtils.isNoneBlank(jxlName)){
	        	   mt.setOperatorType(jxlName);
	               mt.setProvince(obj.getString("province"));
	               msg = messageTemplateService.findTemplate(mt);
	        }
            String sendMsg = "";
            if(msg != null && StringUtils.isNotBlank(msg.getTemplate())){
            	sendMsg = msg.getTemplate();
            }
            if(jxlType.equals("2")){
            	String msgs = sendMsg.substring(0, sendMsg.lastIndexOf("#")+1);
            	String idNumber = user.getIdNumber().substring(user.getIdNumber().length()-6);
            	sendMsg = msgs + idNumber;
            }
            //电信的号码发送的短信格式为MMCZ#用户名#身份证号码
			if(jxlType.equals("3")){
				StringBuffer sb = new StringBuffer();
				String a = "#";
				String username = user.getRealname();
				String idNumber = user.getIdNumber();
				sb.append("MMCZ");
				sb.append(a);
				sb.append(username);
				sb.append(a);
				sb.append(idNumber);
				sendMsg = sb.toString();
			}
            JSONObject data = new JSONObject();
            data.put("sendMsg", sendMsg);
            data.put("sendPhone", sendPhone);
            data.put("province", obj.getString("province"));
            data.put("jxlName", jxlName);
            data.put("phone", phone);
            data.put("jxlType", jxlType);
            rest.setData(data);
        	rest.setCode(json.getString("retCode"));
			rest.setMsg(json.getString("msg"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		SpringUtils.renderJson(response, rest);

	}
	@RequestMapping("/credit-web2/tz")
	public void tz(HttpServletRequest request, HttpServletResponse response, @RequestBody String json) {
		try {
			logger.info("recive from mx call back json=" + json);
			String sucKey = Constant.MX_CALL_BACK_SUC;
			String failKey = Constant.MX_CALL_BACK_FAIL;
			JSONObject jsonObject = JSONObject.fromObject(json);
			String userId = jsonObject.getString("user_id");
			String value = null;
			String key = "";
			if (jsonObject.getBoolean("result")) {
				value = jsonObject.getString("task_id");
				key = sucKey + userId;
			} else {
				key = failKey + userId;
				value = jsonObject.getString("message");
			}
			jedisCluster.setex(key, 24 * 60 * 60, value);
			logger.info("put redis from mx call back json=" + json);
			response.setStatus(HttpServletResponse.SC_CREATED);
		} catch (Exception e) {
			logger.error("tz", e);
		}
	}
}
